<template>
	<!-- 订单tab -->
	<view class="tab-container">
		<view class="uTabs" v-if="isShowTop">
			<u-tabs :list="list" lineWidth='26' lineColor='#44D4A8' :activeStyle="{color:'#44D4A8'}"></u-tabs>
		</view>
		<scroll-view class="tab-scroll" scroll-x="true" :show-scrollbar="false" :scroll-left="scrollLeft">
			<view class="tab-list">
				<view v-for="(item, index) in tabList" :key="index" class="tab-item"
					:class="{ active: currentTab === index }" @click="switchTab(index)">
					<text class="tab-text">{{ item.name }}</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: "customTabs",
		props: {
			isShowTop: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				list: [{
					name: '上门预约',
				}, {
					name: '机构兼职',
				}],
				currentTab: 0,
				scrollLeft: 0,
				tabList: [{
						name: '全部'
					},
					{
						name: '待付款'
					},
					{
						name: '待进行'
					},
					{
						name: '进行中'
					},
					{
						name: '已完成'
					},
					{
						name: '已取消'
					}
				]
			}
		},
		methods: {
			switchTab(index) {
				this.currentTab = index;

				// 计算滚动位置，确保选中项在可视区域内
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.selectAll('.tab-item').boundingClientRect();
					query.select('.tab-scroll').boundingClientRect();
					query.exec((rects) => {
						const tabRects = rects[0];
						const scrollRect = rects[1];
						const selectedTab = tabRects[index];

						if (selectedTab && scrollRect) {
							const scrollLeft = selectedTab.left - scrollRect.left - (scrollRect.width -
								selectedTab.width) / 2;
							this.scrollLeft = Math.max(0, scrollLeft);
						}
					});
				});

				this.$emit('tabChange', index);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tab-container {
		width: 100%;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.uTabs {
		margin-bottom: 24rpx;
	}

	.tab-scroll {
		width: 100%;
		white-space: nowrap;

		/* 隐藏滚动条 */
		::-webkit-scrollbar {
			display: none;
			width: 0;
			height: 0;
			color: transparent;
		}
	}

	.tab-list {
		display: inline-flex;
	}

	.tab-item {
		flex: 0 0 auto;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 56rpx;
		width: 112rpx;
		font-size: 24rpx;
		margin: 0 10rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		border: 2rpx solid transparent;
		transition: all 0.3s ease;

		/* 未选中状态 */
		.tab-text {
			font-weight: 400;
			color: #333333;
			line-height: 1.4;
		}

		/* 选中状态 */
		&.active {
			background-color: rgba(68, 212, 168, 0.1);
			border-color: $theme-color;

			.tab-text {
				color: $theme-color;
				font-weight: 500;
			}
		}

		/* 点击效果 */
		&:active {
			opacity: 0.7;
			transform: scale(0.98);
		}
	}

	/* 确保第一个和最后一个标签的间距 */
	.tab-list .tab-item:first-child {
		margin-left: 0;
	}

	.tab-list .tab-item:last-child {
		margin-right: 0;
	}
</style>